package cn.tangwei.user.service.impl;

import cn.tangwei.basic.exception.BusinessException;
import cn.tangwei.basic.utils.AjaxRusult;
import cn.tangwei.basic.utils.HttpClientUtils;
import cn.tangwei.basic.utils.MD5Utils;
import cn.tangwei.basic.utils.StrUtils;
import cn.tangwei.user.constants.UserConstants;
import cn.tangwei.user.domain.LoginInfo;
import cn.tangwei.user.domain.User;
import cn.tangwei.user.domain.WxUser;
import cn.tangwei.user.dto.LoginDto;
import cn.tangwei.user.mapper.LoginInfoMapper;
import cn.tangwei.user.mapper.UserMapper;
import cn.tangwei.user.mapper.WxUserMapper;
import cn.tangwei.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 账号密码登录流程
     * @param loginDto
     */
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        // 1.参数不能为空
        if(StringUtils.isEmpty(loginDto.getUsername())||
                StringUtils.isEmpty(loginDto.getPassword())
                || StringUtils.isEmpty(loginDto.getType())){
            throw new BusinessException("用户名或密码错误");
        }
        // 2.查询数据：直接只查询username和type
        LoginInfo loginInfo = loginInfoMapper.loadByLoginDto(loginDto);
        //  查询不到直接报错
        if(loginInfo == null){
            throw new BusinessException("用户名或密码错误");
        }
        // 3.查询到了检验密码
        String salt = loginInfo.getSalt();
        String md5Password = loginInfo.getPassword();
        // 前台登录传过来的密码
        String password = loginDto.getPassword();
        // 需要对比密码
        if(!md5Password.equals(MD5Utils.encrypByMd5(password+salt))){
            // 4.对比不成功直接报错
            throw new BusinessException("用户名或密码错误");
        }
        // 5.对比成功显示登录成功,保存redis token
        String token = UUID.randomUUID().toString();
        // 保存redis并设置过期时间30分钟
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        // 6.返回token和loginInfo
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        // 为了安全，把一些敏感信息置空
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo", loginInfo);
        return map;
    }

    /**
     * 微信登录流程
     * @param params
     * @return
     */
    @Override
    public AjaxRusult wechat(Map<String, String> params) {
        // 再map中获取code
        String code = params.get("code");
        // 判断code不能为空
        if(!StringUtils.hasLength(code)){
            throw new BusinessException("没有授权码");
        }
        // 去微信获取令牌
        String getTokenUrl = UserConstants.WXUSER_GET_TOKEN_URL
                .replace("APPID", UserConstants.APPID)
                .replace("SECRET", UserConstants.SECRET)
                .replace("CODE", code);
        // 1.通过code去微信令牌获取token
        String tokenObjStr = HttpClientUtils.httpGet(getTokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        String accessToken = jsonObject.getString("access_token");// 令牌
        String openId = jsonObject.getString("openid");// 微信号
        // 2.根据微信号openid，查询t_wxuser
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        // 3.判断微信用户是否已经再我们平台绑定过
        if(wxUser != null && wxUser.getUser_id() != null){
            // 直接扫码，免密登录
            LoginInfo loginInfo = loginInfoMapper.loadByUserId(wxUser.getUser_id());
            // 登录成功，保存redis和token
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
            // 返回token和loginInfo
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            // 为了安全，把一些敏感信息置空
            loginInfo.setSalt(null);
            loginInfo.setPassword(null);
            map.put("loginInfo", loginInfo);
            return AjaxRusult.me().setResultObj(map);
        }
        // 4.找不到用户，第一次来登录，让前端直接跳转到绑定页面
        // 并携带token和openId回去
        String binderUrlParams = "http://bugtracker.itsource.cn/binder.html?accessToken="+accessToken+"&openId="+openId;
        return AjaxRusult.me().setSuccess(false).setResultObj(binderUrlParams);
    }

    /**
     * 微信登录绑定流程
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> binder(Map<String, String> params) {
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        // 1.空值判断
        if(!StringUtils.hasLength(phone) ||
                !StringUtils.hasLength(verifyCode) ||
                !StringUtils.hasLength(accessToken) ||
                !StringUtils.hasLength(openId)){
            throw new BusinessException("必要信息为空");
        }
        // 2.验证码是否过期
        Object codeTmp = redisTemplate.opsForValue().get(UserConstants.BUSINESS_BINDER_PREFIX + phone);
        if (codeTmp == null){//  查询不到直接报错
            throw new BusinessException("验证码已过期，请重新获取");
        }
        // 3.验证码查询到了对比验证码是否相等，不区分大小写
        String code = codeTmp.toString().split(":")[0];
        if(!verifyCode.equalsIgnoreCase(code)){
            throw new BusinessException("验证码输入错误");
        }
        // 4.手机号不能被注册
        User userTmp = userMapper.loadByPhone(phone);
        User user = null;
        LoginInfo loginInfo = null;
        if (userTmp != null){// 表示手机号已经被注册，可以直接绑定微信用户
            user = userTmp;
            loginInfo = loginInfoMapper.queryById(user.getLogininfo_id());
        }else {// 没有注册，我们需要自己创建一个用户
            user = initUser(phone);
            loginInfo = user2LoginInfo(user);
            loginInfoMapper.save(loginInfo);
            user.setLogininfo_id(loginInfo.getId());
            userMapper.save(user);
        }
        // 5.通过token和openId获取微信用户信息
        String getUserUrl = UserConstants.WXUSER_GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserTmp = HttpClientUtils.httpGet(getUserUrl);
        // 生成wxuser信息并绑定平台用户
        WxUser wxUser = initWxUser(wxUserTmp,user);
        wxUserMapper.save(wxUser);
        // 6.直接扫码，免密登录，登录成功保存redis和token
        String token = UUID.randomUUID().toString();
        // 保存redis并三十分种过期时间
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        // 返回token和loginInfo
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo", loginInfo);
        return map;
    }

    private WxUser initWxUser(String wxUserTmp, User user) {
        // 转换微信用户信息
        JSONObject jsonObject = JSONObject.parseObject(wxUserTmp);
        WxUser wxUser = new WxUser();
        wxUser.setUser_id(user.getId());//绑定用户
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setAddress(null);
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        return wxUser;
    }

    private LoginInfo user2LoginInfo(User user) {
        LoginInfo loginInfo = new LoginInfo();
        // 属性同名原则将user复制给loginInfo
        BeanUtils.copyProperties(user, loginInfo);
        loginInfo.setType(1);// type=1是用户登录
        return loginInfo;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 使用盐值加密之后的密码，通过短信给用户
        String md5 = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }
}
